package com.project.sianet.data.HttpClient;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.project.sianet.R;
import com.project.sianet.data.Client.LibretaClient;
import com.project.sianet.entidades.Competencia;
import com.project.sianet.entidades.Libreta;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
//import android.util.Log;

public class LibretaHttpClient implements LibretaClient {

	private final Context context;
    private final HttpClient httpClient;
//    private final SessionManager session;

    public LibretaHttpClient(Context context) {
    	
    	this.context = context;
//    	this.session = new SessionManager(context);
        
        BasicHttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
        HttpProtocolParams.setUseExpectContinue(params, false);
        httpClient = new DefaultHttpClient(params);
    	
    }
    
    @Override
	public List<Libreta> Libreta_getAllByAlumno(String login, String perfil) {
    	
		List<Libreta> result = new ArrayList<Libreta>();
		String content = get("Alumno_getLibreta/" + login + "/" + perfil);
		
		if (content != null) {
			
			try {
				JSONTokener tokener = new JSONTokener(content);
				JSONArray array = (JSONArray) tokener.nextValue();
				for (int i = 0; i < array.length(); i++) {
                    JSONObject obj = array.getJSONObject(i);

                    Libreta l = new Libreta();
                    l.setCodigoAlumno(obj.isNull("CodigoAlumno") ? "" : obj.getString("CodigoAlumno"));
                    l.setNumeroOrden(obj.isNull("NumeroOrden") ? null : obj.getString("NumeroOrden"));
                    l.setBimestre(obj.isNull("Bimestre") ? null : obj.getString("Bimestre"));
                    l.setCantidadBimestres(obj.isNull("CantidadBimestres") ? 4 : obj.getInt("CantidadBimestres"));
                    l.setCodigoCurso(obj.getInt("CodigoCurso"));
                    l.setArea(obj.isNull("Area") ? null : obj.getString("Area"));
                    l.setCurso(obj.isNull("Curso") ? null : obj.getString("Curso"));
                    l.setGrupo(obj.isNull("Grupo") ? null : obj.getString("Grupo"));
                    l.setNivel(obj.getInt("Nivel"));
                    l.setNota1(obj.isNull("Nota1") ? "" : obj.getString("Nota1"));
                    l.setNota2(obj.isNull("Nota2") ? "" : obj.getString("Nota2"));
                    l.setNota3(obj.isNull("Nota3") ? "" : obj.getString("Nota3"));
                    l.setNota4(obj.isNull("Nota4") ? "" : obj.getString("Nota4"));
                    l.setNota5(obj.isNull("Nota5") ? "" : obj.getString("Nota5"));
                    l.setNota6(obj.isNull("Nota6") ? "" : obj.getString("Nota6"));
                    l.setNota7(obj.isNull("Nota7") ? "" : obj.getString("Nota7"));
                    l.setNota8(obj.isNull("Nota8") ? "" : obj.getString("Nota8"));
                    l.setNota9(obj.isNull("Nota9") ? "" : obj.getString("Nota9"));
                    l.setNota10(obj.isNull("Nota10") ? "" : obj.getString("Nota10"));
                    l.setNota11(obj.isNull("Nota11") ? "" : obj.getString("Nota11"));
                    l.setNota12(obj.isNull("Nota12") ? "" : obj.getString("Nota12"));
                    l.setNotaFinal(obj.isNull("NotaFinal") ? "" : obj.getString("NotaFinal"));
                    l.setTutor(obj.isNull("Tutor") ? null : obj.getString("Tutor"));
                    l.setEsArea(obj.getBoolean("EsArea"));

                    result.add(l);
                }
			} catch (Exception ex) {
				ex.printStackTrace();
			}    
			
		}
		
		return result;
	}
    
    @Override
	public List<Competencia> Libreta_getDetalleByAlumno(String login,
			String perfil, String ccgrado, String bimestre) {
    	
    	List<Competencia> result = new ArrayList<Competencia>();
		String content = get("Alumno_getLibretaDetalle/" + login + "/" + perfil + "/" + ccgrado + "/" + bimestre);
		
		if (content != null) {
			
			try {
				JSONTokener tokener = new JSONTokener(content);
				JSONArray array = (JSONArray) tokener.nextValue();
				for (int i = 0; i < array.length(); i++) {
                    JSONObject obj = array.getJSONObject(i);

                    Competencia c = new Competencia();
                    c.setCodigo(obj.getInt("Codigo"));
                    c.setCodigoPadre(obj.getInt("CodigoPadre"));
                    c.setNivel(obj.getInt("Nivel"));
                    c.setOrden(obj.getInt("Orden"));
                    c.setNombre(obj.isNull("Nombre") ? null : obj.getString("Nombre"));
                    c.setNota(obj.isNull("Nota") ? "-" : obj.getString("Nota"));
                    
                    result.add(c);
                }
			} catch (Exception ex) {
				ex.printStackTrace();
			}    
			
		}
		
		return result;
	}
    
	private String get(String path) {
        try {
            HttpGet request = new HttpGet(getRequestURI(path));
//            request.setHeader("Authorization", SessionManager.getToken());
            HttpResponse res = httpClient.execute(request);
            String content = EntityUtils.toString(res.getEntity());
            return content;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    private URI getRequestURI(String path) throws URISyntaxException {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        String host = context.getString(R.string.pref_host_default) + prefs.getString("ColegioPF", "");
        URI requestURI = new URI(host + "/MobileService.svc/" + path);
        return requestURI;
    }

}
